import torch
import torchvision
from torch import nn
from torch.nn import Sequential, Conv2d, MaxPool2d, Flatten, Linear
from torch.utils.data import DataLoader

dataset = torchvision.datasets.CIFAR10("./dataset",train=False,transform=torchvision.transforms.ToTensor(),download=True)
dataloader = DataLoader(dataset,batch_size=1)


class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.model1 = Sequential(
            Conv2d(3, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 32, 5, padding=2),
            MaxPool2d(2),
            Conv2d(32, 64, 5, padding=2),
            MaxPool2d(2),
            Flatten(),
            Linear(1024, 64),
            Linear(64, 10)
        )

    def forward(self,x):
        x = self.model1(x)
        return x


loss = nn.CrossEntropyLoss()
mymodule = MyModule()
#使用随机梯度下降优化器
optim = torch.optim.SGD(mymodule.parameters(),lr=0.01)#第一个参数表示网络的参数，第二个参数为学习率，在训练网络的时候，
# 一般刚开始会将学习率设置的比较大，后面会将学习率设置的比较小
#下面进行模型的训练
for epoch in range(20):
    running_loss = 0.0
    for data in dataloader:
        imgs,targets = data
        outputs = mymodule(imgs)
        result_loss = loss(outputs,targets)
        #梯度清零
        optim.zero_grad()
        #通过反向传播获取参数梯度
        result_loss.backward()
        #使用优化器step()通过改变梯度优化参数
        optim.step()
        running_loss = running_loss+result_loss
    print(running_loss)